package br.com.amadeus.android.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import br.com.amadeus.android.activities.home.R;
import br.com.amadeus.android.business.FacadeAmadeusDroid;
import br.com.amadeus.android.entities.Course;
import br.com.amadeus.android.util.ConstantsAmadeusDroid;

public class ServiceEndDateCourse extends Service implements Runnable {
	
	protected static final String CATEGORIA = "curso";

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		new Thread(this).start();
	}

	public void run() {
		
		Date dataAtual = new Date();
		List<Course> listCourse = FacadeAmadeusDroid.getInstance(this).getListCourse();
		ArrayList<Course> endDateList = new ArrayList<Course>();
		for (Course course : listCourse) {
			if (!(course.getBeginDate().before(dataAtual) && course.getEndDate().after(dataAtual)) && course.getActive().equals("S")) {
				course.setActive("N");
				endDateList.add(course);
			}
		}
		
		for (Course course : endDateList) {
			FacadeAmadeusDroid.getInstance(this).updateCourse(course);
		}
		
		if (endDateList.size() > 0) {
			createNotification();
		}
		stopSelf();
	}

	private void createNotification() {
		
		String mensagemBarraStatus = ConstantsAmadeusDroid.TICKER_TEXT_NOTIFICATION;

		CharSequence titulo = ConstantsAmadeusDroid.TITLE_NOTIFICATION;

		String mensagem = ConstantsAmadeusDroid.MESSAGE_NOTIFICATION_FIM_COURSE;

		NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

		Intent it = new Intent("HOME");

		PendingIntent p = PendingIntent.getActivity(this, 0, it, 0);

		Notification n = new Notification(R.drawable.amadeus_notification, mensagemBarraStatus, System.currentTimeMillis());

		n.setLatestEventInfo(this, titulo, mensagem, p);

		n.vibrate = new long[] { 100, 250, 100, 500 };

		nm.notify(R.string.app_name, n);
		
	}

}
